<template>
  <div class="app-container preset-log">
    <div v-if="$route.query.formName || $route.query.name || $route.query.ip" class="back-title">
      <i class="el-icon-arrow-left" @click="$router.go(-1)">返回</i>
    </div>
    <div style="height: 100%">
      <div class="container-box">
        <div class="container-search">
          <el-form
            :inline="true"
            :model="formInline"
            class="demo-form-inline"
            style="position: relative"
            @submit.native.prevent
          >
            <el-row class="container-search-row">
              <el-col class="search-col-flex" :span="24">
                <el-form-item label="关键字">
                  <el-input
                    v-model="formInline.keyword"
                    placeholder="请输入关键字"
                    clearable
                    @keyup.enter.native="handleClickSeach"
                  />
                </el-form-item>
                <el-form-item class="el-form-item-radius" label="产生时间">
                  <el-radio-group
                    v-model="formInline.shortcut"
                    class="el-radio-radius"
                    @change="handleTimeRange($event)"
                  >
                    <el-radio-button label="近一日" />
                    <el-radio-button label="近一周" />
                    <el-radio-button class="el-radio-button-radius" label="近一月" />
                  </el-radio-group>
                  <el-date-picker
                    ref="dataPickerRef"
                    v-model="formInline.time"
                    class="data-picker-radius"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :default-time="['00:00:00', '00:00:00']"
                    @change="handleChangeDatePicker"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleClickSeach">查询</el-button>
                  <el-button
                    id="seniorBtn"
                    :icon="showHighSearch ? 'el-icon-arrow-down' : 'el-icon-arrow-up'"
                    @click="handleTiggleSearch"
                  >
                    高级查询
                  </el-button>
                  <el-button @click="handleResetSearch">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="showHighSearch" class="container-search-row high-search-row">
              <el-col v-for="(item, index) in formInline.highSearchParams" :key="index" :span="24">
                <el-select v-model="item.andOr" class="search-form-item" placeholder="请选择">
                  <el-option
                    v-for="i in dictOptions.researchTypeOptions"
                    :key="i.value"
                    :label="i.label"
                    :value="i.value"
                  />
                </el-select>
                <el-select
                  v-model="item.field"
                  class="search-form-item"
                  clearable
                  placeholder="请选择"
                  @change="handleFile($event, item, index)"
                >
                  <el-option
                    v-for="i in dictOptions.researchSearchFiledOptions"
                    :key="i.value"
                    :label="i.label"
                    :value="i.value"
                  />
                </el-select>
                <el-input
                  v-if="item.field == 'custom'"
                  v-model="item.custom"
                  clearable
                  class="search-form-item"
                  placeholder="请输入自定义内容"
                />
                <el-select v-model="item.symbols" class="search-form-item" placeholder="请选择" clearable>
                  <el-option
                    v-for="i in dictOptions.symbolsTypeOptions"
                    :key="i.value"
                    :label="i.label"
                    :value="i.value"
                  />
                </el-select>
                <el-date-picker
                  v-if="item.field == 'entryTime' || item.field == 'operation_time'"
                  v-model="item.value"
                  class="search-form-item"
                  clearable
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期"
                />
                <el-input
                  v-if="item.field != 'entryTime' && item.field != 'operation_time'"
                  v-model="item.value"
                  clearable
                  class="search-form-item"
                  placeholder="请输入"
                />
                <el-button icon="el-icon-close" @click="handleDelBth(index)"> 删除 </el-button>
                <el-button
                  v-if="formInline.highSearchParams.length - 1 == index"
                  type="primary"
                  icon="el-icon-plus"
                  @click="handleAddBtn"
                >添加
                </el-button>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="page-container">
          <!-- 左侧 -->
          <LogTraceFilter ref="logTraceFilterRef" :tree="treeData" @emitSel="getSel" @handleReset="handleReset" />

          <div class="right-container log-right">
            <el-tabs v-model="activeName" @tab-click="handleTabsClick">
              <!-- <el-tab-pane label="列表" name="first">
                <HkTable
                  :loading="loading"
                  :table-data="tableData"
                  :table-columns="tableLabelLists"
                  :query-params="queryParams"
                  :operate="true"
                  :show-index="true"
                  :total="total"
                  :table-height="80"
                  :is-need-index="true"
                  @changePage="handChangePage"
                >
                  <template #operate="scope">
                    <el-button type="text" @click="handleDetail(scope.row)">详情</el-button>
                  </template>
                </HkTable>
              </el-tab-pane> -->
              <el-tab-pane label="时间轴" name="second">
                <LogTraceTimeLine
                  ref="log_trace"
                  :table-data="tableData"
                  :total="total"
                  :search-key="searchKey"
                  @handleDetail="handleTimeLineDetail"
                />
                <pagination
                  background
                  :page.sync="queryParams.current"
                  :limit.sync="queryParams.size"
                  :total="total"
                  layout="total, sizes, prev, pager, next"
                  @pagination="handChangePage"
                />
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </div>
    </div>
    <LogTraceDetail ref="dialogDetailsRef" :gid="currentGid" />
  </div>
</template>

<script>
import HkTable from '@/components/Hk-Table'
import LogTraceFilter from '../components/CommonFilter'
import { listByType, tableList, detailList, getSizerTree } from '@/api/dispose/logTracing'
import LogTraceTimeLine from '../components/LogTraceTimeLine'
import LogTraceDetail from '../components/LogTraceDetail'
import { parseTime } from '@/utils/hongke'

export default {
  components: { HkTable, LogTraceTimeLine, LogTraceDetail, LogTraceFilter },

  data() {
    return {
      formInline: {
        keyword: '',
        region: '',
        time: '',
        highSearchParams: []
      },
      dictOptions: {
        symbolsTypeOptions: [],
        researchSearchFiledOptions: [],
        researchTypeOptions: []
      },
      showHighSearch: false,
      // 树形组件
      treeData: [],
      defaultsourceAppType: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      loading: false,
      tableData: [],
      total: 0,
      queryParams: {
        current: 1,
        size: 10
      },
      tableLabelLists: [
        { label: '产生时间', param: 'entryTime' },
        { label: '日志来源', param: 'data_source_company', width: '200' },
        { label: '日志类型', param: 'source_app_type', width: '200' },
        { label: '日志概要信息', param: 'details' }
      ],
      activeName: 'second',
      detailData: {},
      checkList: [],
      currentGid: '',
      query: {},
      searchKey: null
    }
  },
  created() {
    if(this.$route.query.ip){
      this.$set(this.formInline,'keyword',this.$route.query.ip)
      this.query.keyword=this.$route.query.ip;
    }
    this.getListByType('symbolsType')
    this.getListByType('researchSearchFiled')
    this.getListByType('researchType')
    this.getList({...this.queryParams,...this.formInline})
    this.getLeftTree()
  },
  methods: {
    /** 查询按钮  */
    handleClickSeach() {
      this.searchKey = this.formInline.keyword
      this.queryParams.current = 1
      this.handleSeach()
      this.getLeftTree()
    },
    handleSeach() {
      let startTime = ''
      let endTime = ''
      if (this.formInline?.time != null) {
        startTime = this.formInline?.time[0]
        endTime = this.formInline?.time[1]
      }

      if (this.formInline?.highSearchParams && this.formInline?.highSearchParams.length > 0) {
        const isRequired = this.formInline.highSearchParams.every((i) => {
          return i && i.andOr !== '' && i.field !== '' && i.symbols !== '' && i.value !== '' && i.value != null
        })
        if (!isRequired && this.showHighSearch) return this.$message.error('请完善高级查询')
      }

      this.query = Object.assign({}, this.queryParams, this.formInline, {
        startTime: startTime,
        endTime: endTime,
        filterTree: this.checkList
      })
      //  当高级搜索收起时，搜索时不带高级搜索参数
      if (!this.showHighSearch) {
        this.$delete(this.query, 'highSearchParams')
      }
      this.getList(this.query)
    },
    /** 获取列表数据 */
    getList(query) {
      this.loading = true
      tableList(query).then((res) => {
        this.loading = false
        this.tableData = res.list
        this.total = res.total
      })
    },
    /** 高级查询 */
    handleTiggleSearch() {
      this.showHighSearch = !this.showHighSearch
      if (this.showHighSearch && this.formInline?.highSearchParams.length === 0) {
        this.formInline.highSearchParams.push({ andOr: '', field: '', custom: '', symbols: '', value: '' })
      }
    },
    /** 高级搜索-删除按钮 */
    handleDelBth(index) {
      this.formInline.highSearchParams.splice(index, 1)
      if (this.formInline.highSearchParams.length === 0) {
        this.showHighSearch = false
      }
    },
    /** 高级搜索-添加 */
    handleAddBtn() {
      this.formInline.highSearchParams.push({ andOr: '', field: '', custom: '', symbols: '', value: '' })
    },
    /** 三种时间区间选择*/
    handleTimeRange(value) {
      const end = new Date()
      const start = new Date()
      let nstart
      let nend
      let wstart
      let wend
      let mstart
      let mend
      switch (value) {
        case '近一日':
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
          nstart = this.setStartTime(start.getTime())
          nend = this.setEndTime(start.getTime())
          this.formInline.time = [parseTime(nstart), parseTime(nend)]
          break
        case '近一周':
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
          end.setTime(end.getTime() - 3600 * 1000 * 24 * 1)
          wstart = this.setStartTime(start.getTime())
          wend = this.setEndTime(end.getTime())
          this.formInline.time = [parseTime(wstart), parseTime(wend)]
          break
        case '近一月':
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
          end.setTime(end.getTime() - 3600 * 1000 * 24 * 1)
          mstart = this.setStartTime(start.getTime())
          mend = this.setEndTime(end.getTime())
          this.formInline.time = [parseTime(mstart), parseTime(mend)]
          break
        default:
          break
      }
    },
    // time为某一天的时间戳
    setStartTime(time) {
      const nowTimeDate = new Date(time)
      return nowTimeDate.setHours(0, 0, 0, 0)
    },
    setEndTime(time) {
      const nowTimeDate = new Date(time)
      return nowTimeDate.setHours(23, 59, 59, 999)
    },
    /** 时间转化 */
    timestampToTime(timestamp) {
      const date = new Date(timestamp) // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
      const Y = date.getFullYear() + '-'
      const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      const D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
      const h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
      const m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
      const s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      return Y + M + D + h + m + s
    },
    /** 时间选择器触发事件*/
    handleChangeDatePicker(value) {
      this.formInline.shortcut = ''
      // let timeReduce = (value[1].getTime() - value[0].getTime()) / (3600 * 1000 * 2
    },
    /** 获取高级查询---第一个下拉框*/
    getListByType(query) {
      listByType({ itemType: query }).then((res) => {
        if (query == 'symbolsType') {
          this.dictOptions.symbolsTypeOptions = res.map((i) => {
            return { label: i.itemLabel, value: i.itemVale }
          })
        } else if (query === 'researchSearchFiled') {
          this.dictOptions.researchSearchFiledOptions = res.map((i) => {
            return { label: i.itemLabel, value: i.itemVale }
          })
        } else if (query === 'researchType') {
          this.dictOptions.researchTypeOptions = res.map((i) => {
            return { label: i.itemLabel, value: i.itemVale }
          })
        }
      })
    },
    /** tabs页切换*/
    handleTabsClick(tab, event) {
      this.queryParams = { current: 1, size: 10 }
      this.handleSeach()
    },
    /** file触发事件*/
    handleFile(value, item, index) {
      if (this.formInline.highSearchParams[index]?.value) {
        this.formInline.highSearchParams[index].value = ''
      }
    },
    /** 分页 */
    handChangePage(data) {
      this.queryParams.current = data.page || data.current
      this.queryParams.size = data.limit || data.size
      this.handleSeach()
      this.$nextTick(() => {
        this.$refs.log_trace.scrollToTop()
      })
    },
    /** 详情 */
    handleTimeLineDetail(param) {
      this.currentGid = param.id
      this.$refs.dialogDetailsRef.show(this.currentGid)
    },
    handleDetail(row) {
      this.currentGid = row.row.gid
      this.$refs.dialogDetailsRef.show(this.currentGid)
    },
    /** 获取左侧树的数据 */
    getLeftTree(type) {
      getSizerTree(this.query).then((res) => {
        this.treeData = []
        const result = res
        if (result.length > 0) {
          result.forEach((i, index) => {
            const newChildren = i.children.map((item) => {
              return {
                source: i.value,
                groupName: item.name,
                normalGroupCode: item.value,
                showchild: false,
                children: item.children,
                count: item.count
              }
            })
            // 日志类型
            if (i.value === 'source_app_type') {
              if (type) {
                this.treeData.push(this.defaultsourceAppType)
              } else {
                this.defaultsourceAppType = {
                  showchild: true,
                  groupName: i.name,
                  normalGroupCode: i.value,
                  children: newChildren
                }
                this.treeData.push(this.defaultsourceAppType)
              }
            } else {
              this.treeData.push(
                Object.assign({
                  showchild: true,
                  groupName: i.name,
                  normalGroupCode: i.value,
                  children: newChildren
                })
              )
            }
          })
        }
      })
    },
    /** 左侧树点击事件 */
    getSel(data, checkData) {
      this.checkList = []
      data.forEach((i) => {
        if (i.sourceValues.length > 0) {
          this.checkList.push(i)
        }
      })
      this.queryParams.size = 10
      this.queryParams.current = 1
      this.handleSeach()
      this.$nextTick(() => {
        this.$refs.log_trace.scrollToTop()
      })
      this.$refs.logTraceFilterRef.setChecked(checkData)
    },
    /** 点击左侧树的重置按钮 */
    handleReset() {
      this.checkList = []
      this.handleSeach()
      this.getLeftTree()
    },
    /** 重置按钮 */
    handleResetSearch() {
      this.searchKey = null
      this.queryParams.current = 1
      this.formInline = {
        keyword: null,
        shortcut: null,
        time: [],
        highSearchParams: [{ andOr: '', field: '', custom: '', symbols: '', value: '' }]
      }
      this.checkList = []
      this.$refs.logTraceFilterRef.checkList = []
      this.$refs.logTraceFilterRef.checkKeys = []
      this.showHighSearch = false
      this.handleSeach()
      this.getLeftTree()
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-scrollbar__wrap {
  overflow-x: hidden !important;
  // overflow-y: auto !important;
}
#app.dark-theme {
  .preset-log .left-container {
    border-top: 1px solid rgba(59, 139, 255, 0.4) !important;
  }
  .high-search-row {
    background: rgba(59, 139, 255, 0.2) !important;
  }
}

.el-tab-pane {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.targetTable {
  height: 100%;
}
::v-deep .el-table .cell {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
}
::v-deep .el-radio-button:last-child .el-radio-button__inner {
  border-radius: 0px !important;
}

.el-form-item-radius {
  ::v-deep .el-form-item__content {
    display: flex !important;
    align-items: flex-start !important;
  }
}

.demo-form-inline {
  flex-wrap: wrap;

  .container-search-row {
    .search-form-item {
      width: 15%;
      margin-right: 10px;
    }

    &.high-search-row {
      padding: 10px;
      background: #f3f5fc;
      border-top: 1px solid #4b6eef;
      position: relative;

      &::before {
        display: inline-block;
        content: '';
        position: absolute;
        width: 10px;
        border-bottom: 6px solid #4b6eef;
        border-top: 6px solid transparent;
        border-left: 6px solid transparent;
        border-right: 6px solid transparent;
        top: -13px;
        left: 5%;
      }
    }

    width: 100%;

    .el-col {
      display: flex;
      align-items: flex-end;
      margin-bottom: 10px;
    }

    .data-picker-radius {
      border-left: 0 !important;
      border-radius: 0 4px 4px 0 !important;
    }
  }
}

.preset-log {
  height: 100%;
  padding: 0 !important;
  //background: #eef0f5;

  .page-container {
    //margin-top: 20px;
    //background: #fff;
    align-items: stretch;
    overflow: hidden;
  }

  .el-form {
    display: flex;
  }

  .el-form-item {
    margin-bottom: 0 !important;
  }

  .container-box {
    height: 100%;

    .container-search {
      padding: 0 15px 15px;
      //background: #fff;
    }
  }

  .left-container {
    height: 100%;
    border-top: 0px !important;
  }

  // 跳转的部分
  .m-container {
    width: 100%;
    height: 100%;
    background: #e5ecf6;
    padding: 10px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    font-size: 14px;
    // 头部
    .m-header {
      background: #fff;
      box-shadow: 0 0 40px 0 rgb(0 0 0 / 8%);
      border-radius: 4px;
      margin-bottom: 10px;
    }

    // 线
    .header-line {
      width: 100%;
      height: 38px;
      line-height: 38px;
      padding: 0 8px;
      border-bottom: 1px solid #e8e8e8;
      cursor: pointer;
    }

    .filter-source {
      padding: 10px 16px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .drawmain {
      padding: 0 16px 10px 16px;

      .addSearchParam-container {
        max-height: 265px;
        height: 100%;
        overflow: auto;

        .one-level-search-content {
          position: relative;
          padding-left: 40px;
          padding-bottom: 4px;

          .change-one-level-btn {
            position: absolute;
            left: 0;
            top: calc(50% - 6px);
            z-index: 3;
            padding: 0;
            width: 24px;
            height: 24px;
            color: #2979ff;
            border: none;
            background: #edf5ff;
            border-radius: 2px;
          }

          .addSearchParam {
            width: 100%;
            margin-bottom: 8px;
            position: relative;
            display: flex;
            flex-direction: column;
            min-height: 20%;
            background-color: #f8f9fc;
            border: 1px solid #f0f0f0;

            &::after {
              content: '';
              position: absolute;
              top: -11px;
              left: -29px;
              bottom: -11px;
              border-left: 1px solid #cfe4fe;
            }

            .content {
              flex: 1;
              overflow-y: auto;
              display: flex;
              padding: 16px;
              justify-content: space-between;
              align-items: end;

              & > div {
                width: 60%;
                height: 100%;
                overflow-y: auto;
              }

              .searchContent {
                display: table;
                max-height: 93%;
                position: relative;
                padding-left: 29px;
              }

              .add-btn {
                padding-left: 10px;
              }
            }
          }
        }
      }
    }
  }

  .params-item {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    position: relative;

    &::after {
      content: '';
      position: absolute;
      top: -4px;
      left: -15px;
      bottom: -15px;
      border-left: 1px solid #cfe4fe;
    }

    .params-input {
      margin-right: 8px;
    }
  }

  .add-search-bottom {
    display: flex;
    justify-content: space-between;
    padding-left: 40px;
  }

  .l-container {
    background: #fff;
    width: 100%;
    height: 100%;
    overflow: hidden;

    .total {
      padding: 8px;
      font-size: 14px;
    }
  }
  .el-tabs {
    display: flex;
    flex-direction: column;
    height: 100%;
    overflow: hidden;
  }
}
::v-deep .el-tabs__content {
  // overflow: auto !important;
  position: relative;
  flex: 1 !important;
}
::v-deep .el-tabs__nav-wrap::after {
  background: transparent !important;
}
</style>
